package com.zx.cloud.service;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.time.OffsetDateTime;
import java.util.HashMap;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.zx.cloud.domain.LoanOrder;
import com.zx.cloud.domain.RepayDetail;
import com.zx.cloud.domain.RepayOrder;
import com.zx.cloud.persistence.CrudMapper;
import com.zx.cloud.persistence.LoanOrderMapper;
import com.zx.cloud.persistence.RepayDetailMapper;
import com.zx.cloud.persistence.RepayOrderMapper;
import com.zx.cloud.util.SmsCodeUtil;
/**
 * 批量放款Service
 */
@SpringBootApplication
@Transactional
@Service
public class BatchLendingService extends CrudServiceImpl<LoanOrder> {
	@Autowired
	public BatchLendingService(CrudMapper<LoanOrder> mapper) {
		super(mapper);
		// TODO Auto-generated constructor stub
	}

	private static final Logger LOGGER = LoggerFactory.getLogger(LoanOrderService.class);

	@Autowired
	private LoanOrderMapper loanOrderMapper;
	@Autowired
	private OrderLogService orderLogService;
	@Autowired
	private RepayDetailMapper repayDetailMapper;
	@Autowired
	private RepayOrderMapper repayOrderMapper;
	
	@Autowired
	private DictService dictService;
	/**
	 * @Description:批量放款 更新放款状态为已放款状态   0审核中，1审核失败（拒绝），2审核通过（未放款），3已放款，4已到账
	 * @author zhangshuai
	 * @Create Time: 2017年12月21日下午16:38:40
	 */
	public int updateLoanOrderState(LoanOrder loanOrder,Long userId) {
		/**放款信息*/
		LoanOrder queryLOrder=new LoanOrder();
		queryLOrder.setId(loanOrder.getId());
		LoanOrder  loanOrderData=loanOrderMapper.getLoanOrderInfo(queryLOrder);
		
		Map<String, Object> payResultMap = new HashMap<String, Object>();
		try {
			      LOGGER.info("==============借款管理-放款订单列表-放款=============");
//			       payResultMap=payForService.handlePayment(loanOrderData);
//				   String code=(String) payResultMap.get("resultCode");
//				   if("3000".equals(code)){
			      
					    OffsetDateTime  loanTime=OffsetDateTime.now();//放款时间
					    loanOrderData.setLoanTime(loanTime);
						Integer loanTerm=loanOrderData.getLoanTerm();//借款期限
						OffsetDateTime  expirationTime=loanTime.plusDays(loanTerm.longValue());//到期时间
						loanOrderData.setExpirationTime(expirationTime);
					    /**修改借款订单*/
						updateLoanOrderByDoLending(loanOrderData);
						/**生成还款记录*/
						insertRepayOrderByDoLending(loanOrderData);
						/**交易记录*/
						insertRepayDetailByDoLending(loanOrderData, payResultMap,1);
						try {
						/**放款短信*/
							loanSendSMS(loanOrderData, userId);
						} catch (Exception e) {
							e.printStackTrace();
						}
						/**订单操作日志*/
						orderLogService.insertOrderLog(userId,loanOrder.getId(),1,"放款成功");
						return 1;
//				   }else{
//					   /**交易记录*/
//					  insertRepayDetailByDoLending(loanOrderData, payResultMap,2);
//					   /**订单操作日志*/
//					  orderLogService.insertOrderLog(userId,loanOrder.getId(),1,"放款失败，请查看交易记录");
//					  return 2;
//				   }
		     
          } catch (Exception e) {
        	  e.printStackTrace();
        	  return 2;
		   }
		
	}
	
	/**
	 * @Description:修改借款订单
	 */
	private  void updateLoanOrderByDoLending(LoanOrder loanOrderData){
		/**修改借款订单*/
		LoanOrder  newLoanOrder=new LoanOrder();
		newLoanOrder.setId(loanOrderData.getId());
		newLoanOrder.setStatus(3);//已放款(放款中)
		newLoanOrder.setLoanTime(loanOrderData.getLoanTime());//放款时间
		newLoanOrder.setExpirationTime(loanOrderData.getExpirationTime());//到期时间
		newLoanOrder.setPaymentTime(OffsetDateTime.now());//到账时间
		super.update(newLoanOrder);
		
	}
	/**
	 * @Description:生成还款订单
	 */
	private  void  insertRepayOrderByDoLending(LoanOrder loanOrderData){
		/**生成还款订单*/
		RepayOrder repayOrder=new RepayOrder();
		repayOrder.setLoanOrderId(loanOrderData.getId());
		repayOrder.setRepayAmount(loanOrderData.getLoanAmount());
		repayOrder.setOverdueRate(loanOrderData.getOverdueRate());//逾期利率
		repayOrder.setIsOverdue(0);//初始化：未逾期
		repayOrder.setStatus(0);//初始化：未还款
		repayOrder.setBorrowTime(loanOrderData.getCreateTime());//借款时间
		repayOrder.setExpirationTime(loanOrderData.getExpirationTime());//到期时间
		repayOrder.setCreateTime(OffsetDateTime.now());//创建时间
		repayOrderMapper.insert(repayOrder);
	}
	
	/**
	 * @Description:记录交易记录
	 */
	private  void  insertRepayDetailByDoLending(LoanOrder loanOrderData,Map<String, Object> payResultMap,int type){
		/**生成放款流水记录*/
		String serialNumber=(String) payResultMap.get("serialNumber");
		String  request=(String) payResultMap.get("request");
		String  response=(String) payResultMap.get("response");
		RepayDetail repayDetail=new RepayDetail();
		repayDetail.setOrderId(loanOrderData.getId());
		repayDetail.setOrderType(1);
		repayDetail.setAmount(loanOrderData.getActualAmount());//交易金额
		repayDetail.setRepayType(type);//1放款成功，2放款失败
		repayDetail.setCreateTime(OffsetDateTime.now());
		repayDetail.setBank(loanOrderData.getBank());
		repayDetail.setCardNo(loanOrderData.getCardNo());
		repayDetail.setSerialNumber(serialNumber);//交易流水号
		repayDetail.setRequestBody(request);//交易请求
		repayDetail.setResponseBody(response);//交易响应
		repayDetail.setRemark("放款");
		repayDetailMapper.insert(repayDetail);
	}

	/**
	 * 根据订单号获取订单
	 * @param orderNo
	 * @return
	 */
	public LoanOrder getLoanOrderByOrderNo(Map<String, String> param) {
		
		return loanOrderMapper.getLoanOrderByOrderNo(param);
	}
	
	/**
	 * @Description:放款短信
	 */
	private  void  loanSendSMS(LoanOrder loanOrder,Long userId) {
		/**放款短信*/
		Map<String, String> params = dictService.getSmsDataConfig(0);
		StringBuilder content=new StringBuilder();
		
		String  cardNo=loanOrder.getCardNo();
		cardNo=cardNo.substring(cardNo.length()-4, cardNo.length());
		content=content.append(cardNo);
		try {
			params.put("content",   URLEncoder.encode(content.toString(),"utf-8"));
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		params.put("mobile", loanOrder.getPhone());
	    params.put("templateId", "2812");  
		//参数：0 表示该短信为接口短信
	    SmsCodeUtil.sendSmsCode(params);
		/**订单操作日志*/
		orderLogService.insertOrderLog(userId,loanOrder.getId(),1,"发送放款短信:"+content);
	}
}
